#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/BST.h"

int constructBST(NAryNode *temp)
{
	if(temp!=NULL)
	{
		insert_bst_node(&BSTRoot, temp->fd.locationFullPath, temp);	
		constructBST(temp->next);
		constructBST(temp->directories);
		constructBST(temp->files);
	}
	return 1;
}

int freeTree(BSTNode *bstNode)
{
	if(bstNode!=NULL)
	{
		freeTree(bstNode->left);
		freeTree(bstNode->right);
		free(bstNode);
	}
	return 0;
}

int construct_bst_tree()
{
	freeTree(BSTRoot);
	BSTRoot = NULL;
	NAryNode *nAryNode = nAryRoot;
	BSTRoot = insert_bst_node(&BSTRoot, "/", nAryNode);
	constructBST(nAryNode->directories);
	constructBST(nAryNode->files);
	return 1;
}

BSTNode* insert_bst_node(BSTNode **node, char *fileName, NAryNode *nAryNode)
{
	//Case 1: if root is null
	if((*node) == NULL)
	{
		*node = (BSTNode*)malloc(sizeof(BSTNode));
		char *file = (char*)malloc((strlen(fileName)+1)*sizeof(char));
		strcpy(file, fileName);
		(*node)->fileName = file;
		(*node)->left=NULL;
		(*node)->right=NULL;
		(*node)->nAryNode = nAryNode;
		return (*node);
	}
	else
	{
		if(strcmp((*node)->fileName, fileName)<0)
			return insert_bst_node(&((*node)->right), fileName, nAryNode);
		else
			return insert_bst_node(&((*node)->left), fileName, nAryNode);
	}	
}

void inorder(BSTNode *node)
{
	if(node!=NULL)
	{	
		inorder(node->left);
		printf("%s\t", node->fileName);
		inorder(node->right);
	}
}

BSTNode* search_bst_node(char *fileName)
{
	BSTNode *temp = BSTRoot;
	while(temp!=NULL)
	{
		if( strcmp(temp->fileName, fileName)==0 )
			break;
		else if(strcmp(temp->fileName, fileName)<0)
			temp = temp->right;
		else
			temp = temp->left;
	}
/*
	if(temp == NULL)
		printf("NO Match Found");
	else
		printf("Found at location %u", temp);
*/
	return temp;
}

/*
int main()
{
	char input[100];
	while(1)
	{
		scanf("%s", input);
		if(strcmp(input, "exit")==0)
			break;
		insert_bst_node(&root, input);
	}
	inorder(root);
	printf("Input a string to search: ");
	scanf("%s", input);
	search_bst_node(input);
	return 0;
}
*/
